package com.event.util;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 发布方发布事件消息的工具类
 */
@Component
public class EventUtil {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息的方法
     * @param eventType 事件类型 - 路由键
     * @param msg 实现的消息对象
     * @param durable 是否持久化
     */
    public void sendMsg(String eventType, Object msg, boolean durable){

        //消息转换 Object -> byte[]
        byte[] body = SerializationUtils.serialize(msg);

        //将消息封装成消息对象
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setDeliveryMode(durable ? MessageDeliveryMode.PERSISTENT : MessageDeliveryMode.NON_PERSISTENT);
        Message message = new Message(body, messageProperties);

        //
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());//当前消息的唯一id号
        correlationData.setReturnedMessage(message);

        //发布事件
        rabbitTemplate.send("event_exchange", eventType, message, correlationData);
    }

    /**
     * 直接发布非持久化的消息
     * @param eventType
     * @param msg
     */
    public void sendMsg(String eventType, Object msg){
        this.sendMsg(eventType, msg,false);
    }
}


